using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using CaipuGuanliXitong.Models;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using Microsoft.AspNetCore.Authorization;

namespace CaipuGuanliXitong.Controllers;

public class IngredientController : Controller
{
    private readonly CookBookDbContext _context;

    public IngredientController(CookBookDbContext context)
    {
        _context = context;
    }

    // GET: Ingredient/GetAllIngredients
    [HttpGet]
    [AllowAnonymous]
    public IActionResult GetAllIngredients()
    {
        var ingredients = _context.Ingredients.GetList();
        var ingredientDtos = ingredients.Select(i => new {
            id = i.Id,
            name = i.Name,
            unit = i.Unit,
            price = i.Price
        }).ToList();
        
        return Json(ingredientDtos);
    }
    
    // GET: Ingredient
    public async Task<IActionResult> Index(string searchString, string sortOrder, int page = 1)
    {
        const int pageSize = 20; // 修改为新的默认页面大小
        
        ViewBag.CurrentSort = sortOrder;
        ViewBag.IdSortParm = sortOrder == "Id" ? "id_desc" : "Id";
        ViewBag.CategorySortParm = sortOrder == "Category" ? "category_desc" : "Category";
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.SpecificationSortParm = sortOrder == "Specification" ? "specification_desc" : "Specification";
        ViewBag.UnitSortParm = sortOrder == "Unit" ? "unit_desc" : "Unit";
        ViewBag.PriceSortParm = sortOrder == "Price" ? "price_desc" : "Price";
        ViewBag.RemarkSortParm = sortOrder == "Remark" ? "remark_desc" : "Remark";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
        
        var query = _context.Ingredients.AsQueryable().Where(x => !x.IsDeleted);
        
        if (!String.IsNullOrEmpty(searchString))
        {
            query = query.Where(x => x.Name.Contains(searchString));
            ViewBag.CurrentFilter = searchString;
        }
        
        switch (sortOrder)
        {
            case "id_desc":
                query = query.OrderByDescending(x => x.Id);
                break;
            case "Id":
                query = query.OrderBy(x => x.Id);
                break;
            case "category_desc":
                query = query.OrderByDescending(x => x.Category);
                break;
            case "Category":
                query = query.OrderBy(x => x.Category);
                break;
            case "name_desc":
                query = query.OrderByDescending(x => x.Name);
                break;
            case "Specification":
                query = query.OrderBy(x => x.Specification);
                break;
            case "specification_desc":
                query = query.OrderByDescending(x => x.Specification);
                break;
            case "Unit":
                query = query.OrderBy(x => x.Unit);
                break;
            case "unit_desc":
                query = query.OrderByDescending(x => x.Unit);
                break;
            case "Price":
                query = query.OrderBy(x => x.Price);
                break;
            case "price_desc":
                query = query.OrderByDescending(x => x.Price);
                break;
            case "Remark":
                query = query.OrderBy(x => x.Remark);
                break;
            case "remark_desc":
                query = query.OrderByDescending(x => x.Remark);
                break;
            case "Date":
                query = query.OrderBy(x => x.CreatedTime);
                break;
            case "date_desc":
                query = query.OrderByDescending(x => x.CreatedTime);
                break;
            default:
                query = query.OrderBy(x => x.Id);
                break;
        }
        
        var totalItems = await query.CountAsync();
        var ingredients = await query.ToPageListAsync(page, pageSize);
        
        ViewBag.TotalItems = (int)totalItems;
        ViewBag.CurrentPage = page;
        ViewBag.PageSize = pageSize;
        
        return View(ingredients);
    }

    // GET: Ingredient/Details/5
    public IActionResult Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var ingredient = _context.Ingredients.AsQueryable().Where(x => !x.IsDeleted).First(x => x.Id == id.Value);
        if (ingredient == null)
        {
            return NotFound();
        }

        return View(ingredient);
    }

    // GET: Ingredient/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Ingredient/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create([Bind("Category,Name,Specification,Unit,Price,Remark")] Ingredient ingredient)
    {
        if (ModelState.IsValid)
        {
            ingredient.CreatedTime = DateTime.Now;
            ingredient.UpdatedTime = DateTime.Now;
            _context.Ingredients.Insert(ingredient);
            return RedirectToAction(nameof(Index));
        }
        return View(ingredient);
    }

    // GET: Ingredient/Edit/5
    public IActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var ingredient = _context.Ingredients.AsQueryable().First(x => x.Id == id.Value);
        if (ingredient == null)
        {
            return NotFound();
        }
        return View(ingredient);
    }

    // POST: Ingredient/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(int id, [Bind("Id,Category,Name,Specification,Unit,Price,Remark,CreatedTime")] Ingredient ingredient)
    {
        if (id != ingredient.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            ingredient.UpdatedTime = DateTime.Now;
            _context.Ingredients.Update(ingredient);
            return RedirectToAction(nameof(Index));
        }
        return View(ingredient);
    }

    // GET: Ingredient/Delete/5
    public IActionResult Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var ingredient = _context.Ingredients.AsQueryable().First(x => x.Id == id.Value);
        if (ingredient == null)
        {
            return NotFound();
        }

        return View(ingredient);
    }

    // POST: Ingredient/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteConfirmed(int id)
    {
        var ingredient = _context.Ingredients.AsQueryable().First(x => x.Id == id);
        ingredient.IsDeleted = true;
        ingredient.UpdatedTime = DateTime.Now;
        _context.Ingredients.Update(ingredient);
        return RedirectToAction(nameof(Index));
    }
    
    // POST: Ingredient/BatchDelete
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult BatchDelete(int[] ids)
    {
        if (ids == null || ids.Length == 0)
        {
            ViewBag.Message = "未选择任何食材";
            ViewBag.IsSuccess = false;
        }
        else
        {
            try
            {
                var selectedIngredients = _context.Ingredients.AsQueryable().Where(x => ids.Contains(x.Id)).ToList();
                foreach (var ingredient in selectedIngredients)
                {
                    ingredient.IsDeleted = true;
                    ingredient.UpdatedTime = DateTime.Now;
                }
                _context.Ingredients.UpdateRange(selectedIngredients);
                ViewBag.Message = $"成功删除 {ids.Length} 个食材";
                ViewBag.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ViewBag.Message = "删除失败: " + ex.Message;
                ViewBag.IsSuccess = false;
            }
        }
        
        // 重新加载数据
        const int pageSize = 20;
        var query = _context.Ingredients.AsQueryable().Where(x => !x.IsDeleted);
        var totalItems = query.Count();
        var ingredients = query.ToPageList(1, pageSize);
        
        ViewBag.TotalItems = (int)totalItems;
        ViewBag.CurrentPage = 1;
        ViewBag.PageSize = pageSize;
        
        return View("Index", ingredients);
    }
    
    // GET: Ingredient/Export
    public IActionResult ExportToExcel()
    {
        var ingredients = _context.Ingredients.GetList();
        
        // 创建工作簿
        var workbook = new XSSFWorkbook();
        var sheet = workbook.CreateSheet("食材数据");
        
        // 创建表头
        var headerRow = sheet.CreateRow(0);
        headerRow.CreateCell(0).SetCellValue("编号");
        headerRow.CreateCell(1).SetCellValue("类别");
        headerRow.CreateCell(2).SetCellValue("食材名称");
        headerRow.CreateCell(3).SetCellValue("规格");
        headerRow.CreateCell(4).SetCellValue("单位");
        headerRow.CreateCell(5).SetCellValue("单价");
        headerRow.CreateCell(6).SetCellValue("备注");
        headerRow.CreateCell(7).SetCellValue("创建时间");
        headerRow.CreateCell(8).SetCellValue("修改时间");
        
        // 填充数据
        for (int i = 0; i < ingredients.Count; i++)
        {
            var row = sheet.CreateRow(i + 1);
            var ingredient = ingredients[i];
            row.CreateCell(0).SetCellValue(ingredient.Id);
            row.CreateCell(1).SetCellValue(ingredient.Category ?? "");
            row.CreateCell(2).SetCellValue(ingredient.Name);
            row.CreateCell(3).SetCellValue(ingredient.Specification ?? "");
            row.CreateCell(4).SetCellValue(ingredient.Unit);
            row.CreateCell(5).SetCellValue((double)ingredient.Price);
            row.CreateCell(6).SetCellValue(ingredient.Remark ?? "");
            row.CreateCell(7).SetCellValue(ingredient.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
            row.CreateCell(8).SetCellValue(ingredient.UpdatedTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        
        // 调整列宽
        for (int i = 0; i < 9; i++)
        {
            sheet.AutoSizeColumn(i);
        }
        
        // 写入内存流
        var memoryStream = new MemoryStream();
        workbook.Write(memoryStream, true);
        memoryStream.Position = 0;
        
        return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "食材数据.xlsx");
    }
    
    // POST: Ingredient/Import
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult ImportFromExcel(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            ViewBag.Message = "请选择一个文件";
            ViewBag.IsSuccess = false;
            return View("Index", _context.Ingredients.GetList());
        }
        
        try
        {
            var importedCount = 0;
            
            using (var stream = file.OpenReadStream())
            {
                var workbook = new XSSFWorkbook(stream);
                var sheet = workbook.GetSheetAt(0);
                
                // 从第二行开始读取数据（跳过表头）
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    var dataRow = sheet.GetRow(row);
                    if (dataRow == null) continue;
                    
                    // 读取数据
                    var idCell = dataRow.GetCell(0);
                    var categoryCell = dataRow.GetCell(1);
                    var nameCell = dataRow.GetCell(2);
                    var specificationCell = dataRow.GetCell(3);
                    var unitCell = dataRow.GetCell(4);
                    var priceCell = dataRow.GetCell(5);
                    var remarkCell = dataRow.GetCell(6);
                    var createdTimeCell = dataRow.GetCell(7);
                    var updatedTimeCell = dataRow.GetCell(8);
                    
                    // 检查必要字段是否存在
                    if (nameCell == null || string.IsNullOrWhiteSpace(nameCell.ToString())) continue;
                    if (unitCell == null || string.IsNullOrWhiteSpace(unitCell.ToString())) continue;
                    
                    // 判断是插入还是更新
                    int? id = null;
                    if (idCell != null && !string.IsNullOrEmpty(idCell.ToString()))
                    {
                        if (idCell.CellType == CellType.Numeric)
                        {
                            id = (int)idCell.NumericCellValue;
                        }
                        else if (idCell.CellType == CellType.String)
                        {
                            int parsedId;
                            if (int.TryParse(idCell.StringCellValue, out parsedId))
                            {
                                id = parsedId;
                            }
                        }
                    }
                    
                    var name = nameCell.ToString();
                    var category = categoryCell?.ToString();
                    var specification = specificationCell?.ToString();
                    var unit = unitCell.ToString();
                    var remark = remarkCell?.ToString();
                    
                    // 解析价格
                    double price = 0;
                    if (priceCell != null)
                    {
                        if (priceCell.CellType == CellType.Numeric)
                        {
                            price = priceCell.NumericCellValue;
                        }
                        else if (priceCell.CellType == CellType.String)
                        {
                            double parsedPrice;
                            if (double.TryParse(priceCell.StringCellValue, out parsedPrice))
                            {
                                price = parsedPrice;
                            }
                        }
                    }
                    
                    // 解析时间
                    DateTime createdTime = DateTime.Now;
                    DateTime updatedTime = DateTime.Now;
                    
                    if (createdTimeCell != null)
                    {
                        if (createdTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = createdTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                createdTime = dateValue.Value;
                            }
                        }
                        else if (createdTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedCreatedTime;
                            if (DateTime.TryParse(createdTimeCell.StringCellValue, out parsedCreatedTime))
                            {
                                createdTime = parsedCreatedTime;
                            }
                        }
                    }
                    
                    if (updatedTimeCell != null)
                    {
                        if (updatedTimeCell.CellType == CellType.Numeric)
                        {
                            var dateValue = updatedTimeCell.DateCellValue;
                            if (dateValue.HasValue)
                            {
                                updatedTime = dateValue.Value;
                            }
                        }
                        else if (updatedTimeCell.CellType == CellType.String)
                        {
                            DateTime parsedUpdatedTime;
                            if (DateTime.TryParse(updatedTimeCell.StringCellValue, out parsedUpdatedTime))
                            {
                                updatedTime = parsedUpdatedTime;
                            }
                        }
                    }
                    
                    // 如果ID为空，则插入新记录，否则更新现有记录
                    if (!id.HasValue)
                    {
                        // 创建新食材
                        var ingredient = new Ingredient
                        {
                            Category = category,
                            Name = name ?? "",
                            Specification = specification,
                            Unit = unit ?? "",
                            Price = (decimal)price,
                            Remark = remark,
                            CreatedTime = createdTime,
                            UpdatedTime = updatedTime
                        };
                        _context.Ingredients.Insert(ingredient);
                    }
                    else
                    {
                        // 检查是否存在相同ID的食材
                        var existingIngredient = _context.Ingredients.AsQueryable()
                            .Any(x => x.Id == id.Value);
                        
                        if (existingIngredient)
                        {
                            // 更新现有食材
                            var ingredient = _context.Ingredients.AsQueryable()
                                .First(x => x.Id == id.Value);
                            ingredient.Category = category;
                            ingredient.Name = name ?? "";
                            ingredient.Specification = specification;
                            ingredient.Unit = unit ?? "";
                            ingredient.Price = (decimal)price;
                            ingredient.Remark = remark;
                            ingredient.UpdatedTime = updatedTime;
                            _context.Ingredients.Update(ingredient);
                        }
                        else
                        {
                            // 使用指定ID创建新食材
                            var ingredient = new Ingredient
                            {
                                Id = id.Value,
                                Category = category,
                                Name = name ?? "",
                                Specification = specification,
                                Unit = unit ?? "",
                                Price = (decimal)price,
                                Remark = remark,
                                CreatedTime = createdTime,
                                UpdatedTime = updatedTime
                            };
                            _context.Ingredients.Insert(ingredient);
                        }
                    }
                    
                    importedCount++;
                }
            }
            
            ViewBag.Message = $"成功导入 {importedCount} 条食材数据";
            ViewBag.IsSuccess = true;
        }
        catch (Exception ex)
        {
            ViewBag.Message = "导入失败: " + ex.Message;
            ViewBag.IsSuccess = false;
        }
        
        // 重新加载数据
        const int pageSize = 20;
        var query = _context.Ingredients.AsQueryable();
        var totalItems = query.Count();
        var ingredients = query.ToPageList(1, pageSize);
        
        ViewBag.TotalItems = (int)totalItems;
        ViewBag.CurrentPage = 1;
        ViewBag.PageSize = pageSize;
        
        return View("Index", ingredients);
    }
}